package com.gitee.hengboy.html.covert.image;

import com.github.hui.quick.plugin.base.Base64Util;
import com.github.hui.quick.plugin.base.DomUtil;
import com.github.hui.quick.plugin.base.constants.MediaType;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * Html转换Image的配置类
 * 通过PhantomJs来进行转换图片，需要本机环境安装PhantomJs
 * <p>
 * Example：
 * <p>
 * // 执行html转换图片
 * String url = "https://cloud.tencent.com/developer";
 * BufferedImage img = Html2ImageByJsWrapper.renderHtml2Image(url);
 * // 获取图片base64字符串
 * String imageBase64 = DomUtil.toDomSrc(Base64Util.encode(img, "png"), MediaType.ImagePng);
 *
 * @author：于起宇 <p>
 * ================================
 * Created with IDEA.
 * Date：2018/11/15
 * Time：3:42 PM
 * 个人博客：http://blog.yuqiyu.com
 * 简书：http://www.jianshu.com/u/092df3f77bca
 * 码云：https://gitee.com/hengboy
 * GitHub：https://github.com/hengyuboy
 * ================================
 * </p>
 */
public class HtmlToImageWrapper {
    /**
     * 配置phantomjs执行文件所处的位置
     */
    static final String PHANTOM_JS_BIN = "/usr/local/bin/phantomjs";
    /**
     *
     */
    private static PhantomJSDriver phantomJSDriver = getPhantomJs();

    /**
     * 配置PhantomJS驱动相关信息
     * - ssl网址支持
     * - 开启截屏
     * - 开启css搜索支持
     * - 开启js支持
     * - 配置驱动在本地环境的位置，如：/usr/local/bin/xxx等
     *
     * @return 驱动对象
     */
    private static PhantomJSDriver getPhantomJs() {
        //设置必要参数
        DesiredCapabilities dcaps = new DesiredCapabilities();
        //ssl证书支持
        dcaps.setCapability("acceptSslCerts", true);
        //截屏支持
        dcaps.setCapability("takesScreenshot", true);
        //css搜索支持
        dcaps.setCapability("cssSelectorsEnabled", true);
        //js支持
        dcaps.setJavascriptEnabled(true);
        //驱动支持
        dcaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, PHANTOM_JS_BIN);
        //创建无界面浏览器对象
        return new PhantomJSDriver(dcaps);
    }

    /**
     * 执行html转换图片
     *
     * @param url html地址
     * @return 对象对象实例
     * @throws IOException 文件流异常
     */
    public static BufferedImage renderHtml2Image(String url) throws IOException {
        phantomJSDriver.get(url);
        File file = phantomJSDriver.getScreenshotAs(OutputType.FILE);
        return ImageIO.read(file);
    }

    /**
     * 获取图片的base64字符串
     *
     * @param bufferedImage 图片对象
     * @param mediaType     图片文件类型
     * @return base64字符串
     * @throws IOException 文件流异常信息
     */
    public static String getImageBase64(BufferedImage bufferedImage, MediaType mediaType) throws IOException {
        return DomUtil.toDomSrc(Base64Util.encode(bufferedImage, mediaType.getExt()), mediaType);
    }
}
